import 'package:flutter/material.dart';
import 'package:bear_story/views.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../net.dart' as net;
import '../bean/beans.dart';
import '../page/book.dart';
import '../page/more.dart';
import '../main.dart';
import 'package:bear_story/dialog.dart';

abstract class OnJinPingBooksUpdateListener {
  void onJinPingBooksUpdate(Book book);
}

List<OnJinPingBooksUpdateListener> _jinPingBooksUpdateListener = [];

void addOnJinPingBooksUpdateListener(OnJinPingBooksUpdateListener l) {
  _jinPingBooksUpdateListener.add(l);
}

class StoryTabView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return StoryTabViewState();
  }
}

class StoryTabViewState extends State<StoryTabView> with AutomaticKeepAliveClientMixin {
  var bannerIndex = 0;
  List<HomeBanner> banners = [];
  List<Book> jinPinBooks = [];
  List<Book> baoBaoBooks = [];
  List<Book> storyBooks = [];
  bool _dispose = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _dispose = false;
    print("--StoryTabView initState");
    refreshBanners();
    refreshJinPinBooks();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _dispose = true;
    print("--StoryTabView dispose");
  }

  void refreshBanners() {
    net.getHomeBanner().then((v) {
      setState(() {
        if (v != null && v.length > 0) {
          banners.clear();
          banners = v;
          if (_dispose != null && !_dispose) {
            setState(() {});
          }
        }
      });
    });
  }

  void refreshJinPinBooks() {
    net.getBookByClassify("3nEI444g").then((v) {
      if (v != null && v.length > 0) {
        jinPinBooks.clear();
        jinPinBooks = v;
        for (OnJinPingBooksUpdateListener l in _jinPingBooksUpdateListener) {
          l.onJinPingBooksUpdate(jinPinBooks[0]);
        }
        refreshBookExtraInfo(jinPinBooks).then((v) {
          refreshBaoBaoBooks();
          if (_dispose != null && !_dispose) {
            setState(() {});
          }
        });
      }
    });
  }

  void refreshBaoBaoBooks() {
    net.getBookByClassify("JUlE1117").then((v) {
      if (v != null && v.length > 0) {
        baoBaoBooks.clear();
        baoBaoBooks = v;
        refreshStoryBooks();
        if (_dispose != null && !_dispose) {
          setState(() {});
        }
      }
    });
  }

  void refreshStoryBooks() {
    net.getBookByClassify("6IPY000M").then((v) {
      if (v != null && v.length > 0) {
        storyBooks.clear();
        storyBooks = v;
        if (_dispose != null && !_dispose) {
          setState(() {});
        }
      }
    });
  }

  int getJinpingCount() {
    int count = jinPinBooks.length >= 3 ? 3 : jinPinBooks.length;
    if (count <= 0) {
      count = 3;
    }
    return count;
  }

  int getBaobaoCount() {
    int count = baoBaoBooks.length >= 6 ? 6 : baoBaoBooks.length;
    if (count <= 0) {
      count = 6;
    }
    return count;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // TODO: implement build
    var devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
    return Container(
      color: Colors.white,
      child: CustomScrollView(
        slivers: <Widget>[
          SliverList(
              delegate: SliverChildListDelegate(<Widget>[
            Container(
              constraints: BoxConstraints.expand(height: banner_height),
              child: Stack(
                children: <Widget>[
                  getBannerView(),
                  Align(
                    alignment: FractionalOffset.bottomCenter,
                    child: Container(
                      height: main_radius,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(main_radius), topRight: Radius.circular(main_radius))),
                    ),
                  ),
                ],
              ),
            ),
            Padding(
              padding: EdgeInsets.only(
                  top: main_padding_top - main_radius, left: main_padding_left, right: main_padding_left),
              child: TagView(
                "精品推荐",
                onTapMore: () {
                  pushPage(context, MorePage("精品故事", jinPinBooks));
                },
              ),
            ),
          ])),
          SliverPadding(
            padding: EdgeInsets.only(left: main_padding_left, right: main_padding_left, top: main_padding_top),
            sliver: SliverGrid(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  if (jinPinBooks.length == 0) {
                    return Container(
                      child: BookAlbumView(null, centerTitle: true, showPlayCount: true),
                    );
                  } else {
                    return Container(
                        child: BookAlbumView(
                      jinPinBooks[index],
                      centerTitle: true,
                      showPlayCount: true,
                    ));
                  }
                },
                childCount: getJinpingCount(),
              ),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: main_padding_top,
                crossAxisSpacing: main_padding_top,
                childAspectRatio: getAlbumChildAspectRatio(devicePixelRatio, 3),
              ),
            ),
          ),
          SliverList(
              delegate: SliverChildListDelegate(<Widget>[
            Container(
              color: background_color,
              height: 8,
            ),
            Padding(
              padding: EdgeInsets.only(left: main_padding_left, top: main_padding_top, right: main_padding_left),
              child: TagView(
                "宝宝启蒙",
                onTapMore: () {
                  pushPage(context, MorePage("宝宝启蒙", baoBaoBooks));
                },
              ),
            )
          ])),
          SliverPadding(
            padding: EdgeInsets.only(left: main_padding_left, right: main_padding_left, top: main_padding_top),
            sliver: SliverGrid(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  if (storyBooks.length == 0) {
                    return Container(
                      child: BookAlbumView(null),
                    );
                  } else {
                    return Container(
                      child: BookAlbumView(storyBooks[index]),
                    );
                  }
                },
                childCount: getBaobaoCount(),
              ),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: main_padding_top,
                crossAxisSpacing: main_padding_top,
                childAspectRatio: getAlbumChildAspectRatio(devicePixelRatio, 2),
              ),
            ),
          ),
          SliverList(
              delegate: SliverChildListDelegate(<Widget>[
            Container(
              color: background_color,
              height: 8,
            ),
            Padding(
              padding: EdgeInsets.only(left: main_padding_left, top: main_padding_top, right: main_padding_left),
              child: TagView(
                "贝尔故事学堂",
                onTapMore: () {
                  pushPage(context, MorePage("贝尔故事学堂", storyBooks));
                },
              ),
            )
          ])),
          SliverPadding(
            padding: EdgeInsets.only(top: main_padding_top, left: main_padding_left, right: main_padding_left),
            sliver: SliverGrid(
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return Container(
                      child: BookAlbumView(
                        storyBooks[index],
                        centerTitle: false,
                      ),
                    );
                  },
                  childCount: storyBooks.length >= 30 ? 30 : storyBooks.length,
                ),
                gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    mainAxisSpacing: main_padding_top,
                    crossAxisSpacing: main_padding_top,
                    childAspectRatio: getAlbumChildAspectRatio(devicePixelRatio, 2))),
          ),
          SliverPadding(padding: EdgeInsets.only(bottom: play_controller_bar_height))
        ],
      ),
    );
  }

  Widget getBannerView() {
    return ClipRRect(
      borderRadius: BorderRadius.all(Radius.circular(0)),
      child: Container(
        color: Colors.black26,
        constraints: BoxConstraints.expand(height: banner_height),
        child: Swiper(
          itemCount: banners.length,
          itemBuilder: (BuildContext context, int index) {
            return CachedNetworkImage(
              imageUrl: banners[index].url,
              fit: BoxFit.cover,
              placeholder: (context, url) {
                return Container(
                  color: Color(0xffefeff4),
                );
              },
            );
          },
          pagination: SwiperPagination(
              builder:
                  DotSwiperPaginationBuilder(size: 5, activeSize: 7, color: Colors.white54, activeColor: Colors.white)),
          loop: true,
          index: 0,
          autoplay: banners.length > 0,
          autoplayDelay: 3000,
          autoplayDisableOnInteraction: true,
          onTap: (int index) {
            print("onTap $index");
            showLoadingDialog(context);
            net.getBook(banners[index].bookid).then((v) {
              Navigator.of(context).pop();
              pushPage(context, BookPage(v));
            });
          },
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
